<template>
  <div class="add-container">
    <!-- 操作按钮区 -->
    <div class="action-bar">
      <el-button type="primary" @click="submitAdd">提交</el-button>
      <el-button @click="goBack">取消</el-button>
    </div>
    
    <!-- 表头区域 -->
    <el-card class="form-card" shadow="never">
      <template #header>
        <div class="card-header">
          <span>新增种母分娩</span>
        </div>
      </template>
      
      <el-form :model="addForm" :rules="addRules" ref="addFormRef" label-width="120px" class="header-form">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="种母耳号" prop="EweEarTag" required>
              <el-input v-model="addForm.EweEarTag" placeholder="请输入种母耳号" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="分娩日期" prop="LambingDate" required>
              <el-date-picker v-model="addForm.LambingDate" type="date" value-format="YYYY-MM-DD" style="width:100%" placeholder="请选择分娩日期" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="妊娠天数" prop="GestationDays" required>
              <el-input v-model.number="addForm.GestationDays" type="number" placeholder="请输入妊娠天数" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="分娩难易程度" prop="LambingDifficulty">
              <el-select v-model="addForm.LambingDifficulty" placeholder="请选择" style="width:100%">
                <el-option label="顺产" value="顺产" />
                <el-option label="难产" value="难产" />
                <el-option label="助产" value="助产" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="母性表现" prop="MaternalInstinct">
              <el-select v-model="addForm.MaternalInstinct" placeholder="请选择" style="width:100%">
                <el-option label="1分" value="1分" />
                <el-option label="2分" value="2分" />
                <el-option label="3分" value="3分" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="泌乳情况" prop="Lactation">
              <el-select v-model="addForm.Lactation" placeholder="请选择" style="width:100%">
                <el-option label="1分" value="1分" />
                <el-option label="2分" value="2分" />
                <el-option label="3分" value="3分" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="乳房炎情况" prop="Mastitis">
              <el-select v-model="addForm.Mastitis" placeholder="请选择" style="width:100%">
                <el-option label="无" value="无" />
                <el-option label="轻度" value="轻度" />
                <el-option label="中度" value="中度" />
                <el-option label="重度" value="重度" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="羔总羔数" prop="TotalLambCount" required>
              <el-input v-model.number="addForm.TotalLambCount" type="number" placeholder="请输入羔总羔数" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="性别" prop="Gender">
              <el-select v-model="addForm.Gender" placeholder="请选择" style="width:100%">
                <el-option label="公" value="公" />
                <el-option label="母" value="母" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
    
    <!-- 表格区域 -->
    <el-card class="table-card" shadow="never">
      <el-table :data="tableData" border stripe style="width: 100%">
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="LitterNumber" label="胎次编号" width="120" align="center">
          <template #default="scope">
            <el-input v-model="scope.row.LitterNumber" placeholder="请输入胎次编号" size="small" />
          </template>
        </el-table-column>
        <el-table-column prop="Gender" label="性别" width="80" align="center">
          <template #default="scope">
            <el-select v-model="scope.row.Gender" placeholder="请选择" size="small">
              <el-option label="公" value="公" />
              <el-option label="母" value="母" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="TotalLitterWeight" label="羔总重(kg)" width="120" align="center">
          <template #default="scope">
            <el-input-number v-model="scope.row.TotalLitterWeight" :min="0" :precision="2" size="small" />
          </template>
        </el-table-column>
        <el-table-column prop="LiveLambCount" label="活羔总数" width="100" align="center">
          <template #default="scope">
            <el-input-number v-model="scope.row.LiveLambCount" :min="0" size="small" />
          </template>
        </el-table-column>
        <el-table-column prop="LiveLambWeight" label="活羔总重(kg)" width="120" align="center">
          <template #default="scope">
            <el-input-number v-model="scope.row.LiveLambWeight" :min="0" :precision="2" size="small" />
          </template>
        </el-table-column>
        <el-table-column prop="AvgLiveLambWeight" label="活羔均重(kg)" width="120" align="center">
          <template #default="scope">
            <el-input-number v-model="scope.row.AvgLiveLambWeight" :min="0" :precision="2" size="small" />
          </template>
        </el-table-column>
        <el-table-column prop="DeadLambCount" label="死羔总数" width="100" align="center">
          <template #default="scope">
            <el-input-number v-model="scope.row.DeadLambCount" :min="0" size="small" />
          </template>
        </el-table-column>
        <el-table-column prop="DeadLambWeight" label="死羔总重(kg)" width="120" align="center">
          <template #default="scope">
            <el-input-number v-model="scope.row.DeadLambWeight" :min="0" :precision="2" size="small" />
          </template>
        </el-table-column>
        <el-table-column prop="AvgDeadLambWeight" label="死羔均重(kg)" width="120" align="center">
          <template #default="scope">
            <el-input-number v-model="scope.row.AvgDeadLambWeight" :min="0" :precision="2" size="small" />
          </template>
        </el-table-column>
        <el-table-column prop="FatLambBatch" label="肥羊批次" width="100" align="center">
          <template #default="scope">
            <el-input v-model="scope.row.FatLambBatch" placeholder="请输入批次" size="small" />
          </template>
        </el-table-column>
        <el-table-column prop="HealthyLambCount" label="健羔数" width="80" align="center">
          <template #default="scope">
            <el-input-number v-model="scope.row.HealthyLambCount" :min="0" size="small" />
          </template>
        </el-table-column>
        <el-table-column prop="WeakLambCount" label="弱羔数" width="80" align="center">
          <template #default="scope">
            <el-input-number v-model="scope.row.WeakLambCount" :min="0" size="small" />
          </template>
        </el-table-column>
        <el-table-column prop="DeformedLambCount" label="畸形数" width="80" align="center">
          <template #default="scope">
            <el-input-number v-model="scope.row.DeformedLambCount" :min="0" size="small" />
          </template>
        </el-table-column>
        <el-table-column prop="StillbirthCount" label="死胎数" width="80" align="center">
          <template #default="scope">
            <el-input-number v-model="scope.row.StillbirthCount" :min="0" size="small" />
          </template>
        </el-table-column>
        <el-table-column prop="AbnormalFetusCount" label="畸胎数" width="80" align="center">
          <template #default="scope">
            <el-input-number v-model="scope.row.AbnormalFetusCount" :min="0" size="small" />
          </template>
        </el-table-column>
        <el-table-column prop="MummifiedFetusCount" label="木乃伊数" width="100" align="center">
          <template #default="scope">
            <el-input-number v-model="scope.row.MummifiedFetusCount" :min="0" size="small" />
          </template>
        </el-table-column>

        <el-table-column prop="CurrentPen" label="当前栋舍" width="100" align="center">
          <template #default="scope">
            <el-input v-model="scope.row.CurrentPen" placeholder="请输入栋舍" size="small" />
          </template>
        </el-table-column>
        <el-table-column prop="CurrentStall" label="当前栏位" width="100" align="center">
          <template #default="scope">
            <el-input v-model="scope.row.CurrentStall" placeholder="请输入栏位" size="small" />
          </template>
        </el-table-column>
        <el-table-column prop="TransferInPen" label="转入栋舍" width="100" align="center">
          <template #default="scope">
            <el-input v-model="scope.row.TransferInPen" placeholder="请输入栋舍" size="small" />
          </template>
        </el-table-column>
        <el-table-column prop="TransferInStall" label="转入栏位" width="100" align="center">
          <template #default="scope">
            <el-input v-model="scope.row.TransferInStall" placeholder="请输入栏位" size="small" />
          </template>
        </el-table-column>
        <el-table-column prop="TransferOutPen" label="转出栋舍" width="100" align="center">
          <template #default="scope">
            <el-input v-model="scope.row.TransferOutPen" placeholder="请输入栋舍" size="small" />
          </template>
        </el-table-column>
        <el-table-column prop="ResponsiblePerson" label="负责人" width="100" align="center">
          <template #default="scope">
            <el-input v-model="scope.row.ResponsiblePerson" placeholder="请输入负责人" size="small" />
          </template>
        </el-table-column>
        <el-table-column prop="DocumentNumber" label="单据号" width="120" align="center">
          <template #default="scope">
            <el-input v-model="scope.row.DocumentNumber" placeholder="请输入单据号" size="small" />
          </template>
        </el-table-column>
        <el-table-column prop="Status" label="状态" width="100" align="center">
          <template #default="scope">
            <el-input v-model="scope.row.Status" placeholder="请输入状态" size="small" />
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="80" align="center">
          <template #default="scope">
            <el-button link type="danger" size="small" @click="removeDetail(scope.$index)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="table-actions">
        <el-button type="primary" @click="addDetail" icon="el-icon-plus">新增行</el-button>
      </div>
    </el-card>
    
    <!-- 表尾汇总区域 -->
    <el-card class="summary-card" shadow="never">
      <div class="summary-section">
        <span>合计: 数量: {{ totalCount }} | 重量: {{ totalWeight }}kg | 活羔: {{ totalLiveCount }} | 死羔: {{ totalDeadCount }}</span>
      </div>
    </el-card>
    
    <!-- 备注区域 -->
    <el-card class="remark-card" shadow="never">
      <el-form-item label="备注">
        <el-input v-model="addForm.Remark" type="textarea" placeholder="请填写备注信息" />
      </el-form-item>
    </el-card>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { addEweLambing } from '../../utils/requestEweLambing'

const router = useRouter()
const addFormRef = ref()

// 表头表单数据
const addForm = reactive({
  EweEarTag: '',
  LambingDate: '',
  GestationDays: '',
  LambingDifficulty: '',
  MaternalInstinct: '',
  Lactation: '',
  Mastitis: '',
  TotalLambCount: '',
  TotalLitterWeight: '',
  LiveLambCount: '',
  LiveLambWeight: '',
  AvgLiveLambWeight: '',
  DeadLambCount: '',
  DeadLambWeight: '',
  AvgDeadLambWeight: '',
  FatLambBatch: '',
  HealthyLambCount: '',
  WeakLambCount: '',
  DeformedLambCount: '',
  StillbirthCount: '',
  AbnormalFetusCount: '',
  MummifiedFetusCount: '',
  LitterNumber: '',
  Gender: '',
  CurrentPen: '',
  CurrentStall: '',
  TransferInPen: '',
  TransferInStall: '',
  TransferOutPen: '',
  ResponsiblePerson: '',
  DocumentNumber: '',
  Status: '',
  Remark: ''
})

// 表格数据
const tableData = ref([{
  LitterNumber: '',
  Gender: '',
  TotalLitterWeight: 0,
  LiveLambCount: 0,
  LiveLambWeight: 0,
  AvgLiveLambWeight: 0,
  DeadLambCount: 0,
  DeadLambWeight: 0,
  AvgDeadLambWeight: 0,
  FatLambBatch: '',
  HealthyLambCount: 0,
  WeakLambCount: 0,
  DeformedLambCount: 0,
  StillbirthCount: 0,
  AbnormalFetusCount: 0,
  MummifiedFetusCount: 0,
  CurrentPen: '',
  CurrentStall: '',
  TransferInPen: '',
  TransferInStall: '',
  TransferOutPen: '',
  ResponsiblePerson: '',
  DocumentNumber: '',
  Status: ''
}])

// 表单验证规则
const addRules = {
  EweEarTag: [{ required: true, message: '请输入种母耳号', trigger: 'blur' }],
  LambingDate: [{ required: true, message: '请选择分娩日期', trigger: 'change' }],
  GestationDays: [{ required: true, message: '请输入妊娠天数', trigger: 'blur' }],
  TotalLambCount: [{ required: true, message: '请输入羔总羔数', trigger: 'blur' }],
}

// 计算汇总数据
const totalCount = computed(() => {
  return addForm.TotalLambCount || 0
})

const totalWeight = computed(() => {
  return tableData.value.reduce((sum, item) => sum + (Number(item.TotalLitterWeight) || 0), 0)
})

const totalLiveCount = computed(() => {
  return tableData.value.reduce((sum, item) => sum + (Number(item.LiveLambCount) || 0), 0)
})

const totalDeadCount = computed(() => {
  return tableData.value.reduce((sum, item) => sum + (Number(item.DeadLambCount) || 0), 0)
})

// 添加明细行
const addDetail = () => {
  tableData.value.push({
    LitterNumber: '',
    Gender: '',
    TotalLitterWeight: 0,
    LiveLambCount: 0,
    LiveLambWeight: 0,
    AvgLiveLambWeight: 0,
    DeadLambCount: 0,
    DeadLambWeight: 0,
    AvgDeadLambWeight: 0,
    FatLambBatch: '',
    HealthyLambCount: 0,
    WeakLambCount: 0,
    DeformedLambCount: 0,
    StillbirthCount: 0,
    AbnormalFetusCount: 0,
    MummifiedFetusCount: 0,
    CurrentPen: '',
    CurrentStall: '',
    TransferInPen: '',
    TransferInStall: '',
    TransferOutPen: '',
    ResponsiblePerson: '',
    DocumentNumber: '',
    Status: ''
  })
}

// 删除明细行
const removeDetail = (index: number) => {
  if (tableData.value.length > 1) {
    tableData.value.splice(index, 1)
  }
}

function submitAdd() {
  (addFormRef.value as any).validate((valid: boolean) => {
    if (!valid) return
    
    // 验证表格数据
    for (let i = 0; i < tableData.value.length; i++) {
      const row = tableData.value[i]
      if (!row.LitterNumber) {
        ElMessage.error(`第${i + 1}行胎次编号不能为空`)
        return
      }
    }
    
    // 构造payload，使用表头表单数据作为主数据
    // 处理日期格式
    let formattedDate = ''
    if (addForm.LambingDate) {
      if (typeof addForm.LambingDate === 'string') {
        // 如果是字符串格式，直接使用
        formattedDate = addForm.LambingDate
      } else if (addForm.LambingDate && typeof addForm.LambingDate === 'object' && 'toISOString' in addForm.LambingDate) {
        // 如果是Date对象，格式化为ISO字符串
        formattedDate = (addForm.LambingDate as Date).toISOString().split('T')[0]
      } else {
        // 其他情况，尝试转换为字符串
        formattedDate = String(addForm.LambingDate)
      }
    }
    
    const payload = {
      EweEarTag: addForm.EweEarTag || '',
      LambingDate: formattedDate,
      GestationDays: Number(addForm.GestationDays) || 0,
      LambingDifficulty: addForm.LambingDifficulty || '',
      MaternalInstinct: addForm.MaternalInstinct || '',
      Lactation: addForm.Lactation || '',
      Mastitis: addForm.Mastitis || '',
      TotalLambCount: Number(addForm.TotalLambCount) || 0,
      TotalLitterWeight: Number(tableData.value[0]?.TotalLitterWeight) || 0,
      LiveLambCount: Number(tableData.value[0]?.LiveLambCount) || 0,
      LiveLambWeight: Number(tableData.value[0]?.LiveLambWeight) || 0,
      AvgLiveLambWeight: Number(tableData.value[0]?.AvgLiveLambWeight) || 0,
      DeadLambCount: Number(tableData.value[0]?.DeadLambCount) || 0,
      DeadLambWeight: Number(tableData.value[0]?.DeadLambWeight) || 0,
      AvgDeadLambWeight: Number(tableData.value[0]?.AvgDeadLambWeight) || 0,
      FatLambBatch: tableData.value[0]?.FatLambBatch || '',
      HealthyLambCount: Number(tableData.value[0]?.HealthyLambCount) || 0,
      WeakLambCount: Number(tableData.value[0]?.WeakLambCount) || 0,
      DeformedLambCount: Number(tableData.value[0]?.DeformedLambCount) || 0,
      StillbirthCount: Number(tableData.value[0]?.StillbirthCount) || 0,
      AbnormalFetusCount: Number(tableData.value[0]?.AbnormalFetusCount) || 0,
      MummifiedFetusCount: Number(tableData.value[0]?.MummifiedFetusCount) || 0,
      LitterNumber: tableData.value[0]?.LitterNumber || '',
      Gender: tableData.value[0]?.Gender || '',
      CurrentPen: tableData.value[0]?.CurrentPen || '',
      CurrentStall: tableData.value[0]?.CurrentStall || '',
      TransferInPen: tableData.value[0]?.TransferInPen || '',
      TransferInStall: tableData.value[0]?.TransferInStall || '',
      TransferOutPen: tableData.value[0]?.TransferOutPen || '',
      ResponsiblePerson: tableData.value[0]?.ResponsiblePerson || '',
      DocumentNumber: tableData.value[0]?.DocumentNumber || '',
      Status: tableData.value[0]?.Status || '待审核',
      Creator: 'admin',
      Remark: addForm.Remark || ''
    }
    
         console.log('提交数据', payload)
     console.log('API地址:', 'http://39.96.200.62:8511/api/EweLambing/create')
     
     addEweLambing(payload)
       .then(res => {
         console.log('API响应:', res)
         if (res.data && res.data.code === 200) {
           ElMessage.success('新增成功')
           router.push('/EweLambing')
         } else {
           console.error('API返回错误:', res.data)
           ElMessage.error(res.data?.msg || '新增失败')
         }
       })
       .catch(error => {
         console.error('API请求失败:', error)
         console.error('错误详情:', error.response?.data)
         console.error('错误状态码:', error.response?.status)
         ElMessage.error(error.response?.data?.msg || '新增失败，请检查网络连接')
       })
  })
}

function goBack() {
  router.push('/EweLambing')
}
</script>

<style scoped>
.add-container {
  padding: 20px;
  background: #f5f5f5;
  min-height: 100vh;
}

.action-bar {
  margin-bottom: 20px;
  text-align: center;
}

.form-card {
  margin-bottom: 20px;
}

.header-form {
  padding: 20px 0;
}

.table-card {
  margin-bottom: 20px;
}

.table-actions {
  margin-top: 10px;
  text-align: center;
}

.summary-card {
  margin-bottom: 20px;
}

.summary-section {
  background: #fff;
  padding: 15px;
  margin-bottom: 20px;
  border-radius: 4px;
  text-align: right;
  font-weight: bold;
}

.summary-section span {
  margin-left: 20px;
}

.remark-card {
  margin-bottom: 20px;
}

.card-header {
  font-weight: bold;
  font-size: 16px;
}
</style> 